<template>
  <div class="conversations">
    <ul
      v-if="conversationWraps.length"
      v-infinite-scroll="scrollUserList"
      class="shop-list"
      infinite-scroll-immediate="false"
    >
      <li
        v-for="conversationWrap in conversationWraps"
        :key="conversationWrap"
        ref="conversationsRef"
        :class="getConversationItemCss(conversationWrap)"
        class="item-content"
        @click="() => {
          onSelectChannelClick(conversationWrap.channel,conversationWrap.shopName,conversationWrap.shopId,conversationWrap.unread)
        }"
      >
        <div class="left">
          <div
            class="avatar"
            style="width: 48px;height: 48px;"
          >
            <img
              :src="conversationWrap.pic?checkFileUrl(conversationWrap.pic):imAvatarPng"
              alt=""
            >
          </div>
        </div>
        <div class="right">
          <div class="right-item1">
            <div class="title-content">
              <div class="title">
                {{ conversationWrap.shopName }}
              </div>
              <div
                v-if="conversationWrap.shopId===1"
                class="shop-icon"
              >
                {{ '自营' }}
              </div>
              <div
                v-if="conversationWrap.shopId===0"
                class="shop-icon"
              >
                {{ '官方' }}
              </div>
            </div>
            <div class="time">
              {{ conversationWrap.timestampString }}
            </div>
          </div>
          <div class="right-item2">
            <div
              v-if="conversationWrap.lastMessage?.content.text"
              class="last-msg"
            >
              {{ getMessageText(conversationWrap.lastMessage) }}
            </div>

            <div
              v-if="conversationWrap.unread > 0"
              className="reddot"
            >
              {{ conversationWrap.unread }}
            </div>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>
<script setup>
import { WKSDK, ConnectStatus, ConversationAction, Channel, ChannelTypeGroup } from 'wukongimjssdk'
import { ConversationWrap } from './ConversationWrap'
import { Convert } from './convert'
import imAvatarPng from '@/assets/images/chat/imAvatar.png'
import { checkFileUrl } from '@/utils/index.js'
const emit = defineEmits(['channelInfoUpdate'])

const onSelectChannel = defineProps({
  onSelectChannel: {
    type: Function,
    default: () => null
  },
  currentShopId: {
    type: Number,
    default: null
  },
  chatType: {
    type: Number,
    default: null
  }
})

// 获取某个频道的最近会话
const clearConversationUnread = (channel) => {
  const conversation = WKSDK.shared().conversationManager.findConversation(channel)
  if (conversation) {
    conversation.unread = 0
    WKSDK.shared().conversationManager.notifyConversationListeners(conversation, ConversationAction.update)
  }
}

// 排序最近会话列表
const sortConversations = (conversations) => {
  let newConversations = conversations
  if (!newConversations) {
    newConversations = conversationWraps.value
  }
  if (!newConversations || newConversations.length <= 0) {
    return []
  }
  const sortAfter = newConversations.sort((a, b) => {
    let aScore = a.timestamp
    let bScore = b.timestamp
    if (a.extra?.top === 1) {
      aScore += 1000000000000
    }
    if (b.extra?.top === 1) {
      bScore += 1000000000000
    }
    return bScore - aScore
  })
  return sortAfter
}

// 监听连接状态
let shopIds = []
const connectStatusListener = async (status) => {
  const shopId = onSelectChannel.chatType ? 0 : onSelectChannel.currentShopId
  if (status === ConnectStatus.Connected) {
    const remoteConversations = await WKSDK.shared().conversationManager.sync() // 同步最近会话列表
    if (remoteConversations && remoteConversations.length > 0) {
      conversationWraps.value = sortConversations(remoteConversations.map(conversation => new ConversationWrap(conversation)))

      shopIds = conversationWraps.value.map((item) => item.conversation.shopId)
      if (shopIds.includes(shopId)) {
        const results = conversationWraps.value.filter(item => item.conversation.shopId === shopId)[0]
        onSelectChannelClick(results.conversation.channel, results.conversation.shopName, results.conversation.shopId)
      }
    }
    if (!shopIds.includes(shopId)) {
      http.post('/p/wuKongIm/getShopChannelInfo?shopId=' + shopId).then(({ data }) => {
        if (data) {
          WKSDK.shared().conversationManager.createEmptyConversation(new Channel(data.channelId, ChannelTypeGroup))
          conversationWraps.value[0].conversation.pic = data.pic
          conversationWraps.value[0].conversation.shopName = data.shopName
          conversationWraps.value[0].conversation.shopId = data.imChannel.shopId
          onSelectChannelClick(new Channel(data.channelId, ChannelTypeGroup), data.shopName, shopId)
        } else {
          onCreateChannel()
        }
      })
    }
  }
}

const conversationListener = async (conversation, action) => {
  if (conversation.channel.channelID == selectedID) {
    conversation.unread = 0
  }
  if (action === ConversationAction.add) {
    conversationWraps.value = [new ConversationWrap(conversation), ...(conversationWraps.value || [])]
  } else if (action === ConversationAction.update) {
    const index = conversationWraps.value?.findIndex(item => item.channel.channelID === conversation.channel.channelID && item.channel.channelType === conversation.channel.channelType)
    if (isJSON(conversation.lastMessage?.content.text)) {
      conversationWraps.value[index] = new ConversationWrap(conversation)
      conversationWraps.value = sortConversations()
    }
  }
}
// 判断是否为JSON格式
const isJSON = (str) => {
  if (typeof str == 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
}
const selectedChannel = ref() // 选中的频道
let selectedID
let nowChannel
const onSelectChannelClick = async (channel, shopName, shopId, unread) => {
  nowChannel = channel
  selectedID = channel.channelID
  fetchChannelInfoIfNeed(channel)
  http.post('/p/wuKongIm/getShopChannelInfo?shopId=' + shopId).then(async ({ data }) => {
    unread > 0 && await http.post('/p/wuKongIm/conversations/setUnread', { channel_id: channel.channelID, maxSeq: data.imChannel.shopReadSeq })
    clearConversationUnread(channel)
    selectedChannel.value = channel
    if (onSelectChannel) {
      onSelectChannel.onSelectChannel(channel, shopName, shopId, data?.imChannel.shopReadSeq, data.shopStatus)
    }
  })
}

const getConversationItemCss = (conversationWrap) => {
  if (!selectedChannel.value) {
    return 'conversation-item'
  }
  if (selectedChannel.value.isEqual(conversationWrap.channel)) {
    return 'conversation-item selected'
  }
  return 'conversation-item'
}
const conversationWraps = ref([]) // 本地最近会话列表
const conversationsRef = ref(null)

const onCreateChannel = () => {
  const shopId = onSelectChannel.chatType ? 0 : onSelectChannel.currentShopId
  http.post('/p/wuKongIm/createChannel?shopId=' + shopId).then(({ data }) => {
    WKSDK.shared().conversationManager.createEmptyConversation(new Channel(data.channelId, ChannelTypeGroup))
    conversationWraps.value[0].conversation.pic = data.pic
    conversationWraps.value[0].conversation.shopName = data.shopName
    conversationWraps.value[0].conversation.shopId = shopId
    onSelectChannelClick(new Channel(data.channelId, ChannelTypeGroup), data.shopName, shopId)
  })
}
const channelInfoListener = () => {
  conversationWraps.value = [...conversationWraps.value || []] // 强制刷新
}
const getMessageText = (message) => {
  if (isJSON(message.content.text)) {
    message.content.text = JSON.parse(message.content.text)
  }
  if (message.content.text?.type === -1) {
    if (message.content.text.sendTextState) {
      return message.content.text.content
    } else if (message.content.text.sendIssusState) {
      return message.content.text.issues[0].content
    }
  }
  if (message.content.text?.msgType === 1 || message.content.text?.msgType === -1 || message.content.text?.type === -5) {
    return message.content?.text.msg
  } else if (message.content.text?.msgType === 4) {
    return '[商品链接]'
  } else if (!message.content.text?.msgType) {
    return message.content.text?.content || ''
  } else {
    return '[图片]'
  }
}
let pages = 0

const sendDelayedRequest = () => {
  return new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        const response = await http.get('/p/wuKongIm/conversation/sync/page', { params: page })
        const data = response.data.records
        pages = data.pages

        const conversationList = data
        const resultConversations = []

        if (conversationList) {
          conversationList.forEach((v) => {
            const conversation = Convert.toConversation(v)
            conversation.lastMessage.content.text = JSON.parse(conversation.lastMessage?.content.text)
            resultConversations.push(conversation)
          })
        }
        resolve(resultConversations)
      } catch (error) {
        reject(error)
      }
    }, 100)
  })
}
const cmdListener = async (msg) => {
  if (msg.content.contentObj.cmd === 'memberUpdate') {
    WKSDK.shared().channelManager.fetchChannelInfo(nowChannel)
    const remoteConversations = await WKSDK.shared().conversationManager.sync()
    conversationWraps.value = sortConversations(remoteConversations.map(conversation => new ConversationWrap(conversation)))
    emit('channelInfoUpdate')
  }
}

const fetchChannelInfoIfNeed = (channel) => {
  const channelInfo = WKSDK.shared().channelManager.getChannelInfo(channel)// 获取频道详情(不会触发数据源的远程获取)
  if (!channelInfo) {
    WKSDK.shared().channelManager.fetchChannelInfo(channel)
  }
}

const page = {
  version: 0,
  current: 1,
  size: 20
}
const scrollUserList = async () => {
  page.current++
  if (page.current <= pages) {
    const remoteConversations = await WKSDK.shared().conversationManager.sync()
    conversationWraps.value = conversationWraps.value.concat(remoteConversations)
  }
}
// 同步自己业务端的最近会话列表
WKSDK.shared().config.provider.syncConversationsCallback = async () => {
  const data = await sendDelayedRequest()
  return data
}
onMounted(async () => {
  WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener) // 监听连接状态
  WKSDK.shared().conversationManager.addConversationListener(conversationListener) // 监听最近会话列表的变化
  WKSDK.shared().chatManager.addCMDListener(cmdListener) // 监听cmd消息
  WKSDK.shared().channelManager.addListener(channelInfoListener) // 监听频道信息变化
})
onUnmounted(() => {
  WKSDK.shared().conversationManager.removeConversationListener(conversationListener)
  WKSDK.shared().chatManager.removeCMDListener(cmdListener)
  WKSDK.shared().connectManager.removeConnectStatusListener(connectStatusListener)
  WKSDK.shared().channelManager.removeListener(channelInfoListener)
})

</script>

<style lang="scss" scoped>
.conversations {
  width: 30%;
  height: 100%;
  background: #ffffff;
  opacity: 1;
  border-right: 1px solid #eceef0;
  overflow: auto;
  .shop-list {
    margin-bottom: 1px;
  }
}

.item-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;
    text-align: left;
}

.conversation-item {
    display: flex;
    height: 80px;
    width: 100%;
    background-color: white;
    cursor: pointer;
    overflow: hidden;
}

.left {
    height: 100%;
    display: flex;
    align-items: center;
    margin-left: 10px;
}

.right {
    margin-left: 10px;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.right-item1 {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  .title-content{
    display: flex;
    .shop-icon{
      width: 40px;
      height: 20px;
      line-height: 20px;
      font-size: 12px;
      text-align: center;
      font-weight: 400;
      color: #ffffff;
      background: #e1251b;
      border-radius: 2px;
      margin-left: 10px;
    }
  }
}

.right-item2 {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}

.reddot {
    width: 20px;
    height: 20px;
    border-radius: 10px;
    background-color: #fc1b35;
    color: white;
    font-size: 12px;
    text-align: center;
    line-height: 20px;
    margin-right: 10px;
}

.right-item1 .title {
    font-size: 16px;
    font-weight: bold;
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}

.last-msg {
    max-width: 115px;
    font-size: 14px;
    color: #999999;
    margin-top: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}

.time {
    font-size: 12px;
    color: #999999;
    margin-right: 10px;
}

.selected {
    background-color: #d0e9ff;
}

.avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    color: white;
    font-size: 20px;
    text-align: center;
    img {
      width: 100%;
      height: 100%;
      font-size: 0;
    }
}
</style>
